package iec104tcp;

import model.ModusTable;
import service.ModusTableService;
import wei.yigulu.iec104.annotation.AsduType;
import wei.yigulu.iec104.apdumodel.Apdu;
import wei.yigulu.iec104.asdudataframe.BooleanType;
import wei.yigulu.iec104.asdudataframe.typemodel.IeBoolean;
import wei.yigulu.iec104.asdudataframe.typemodel.InformationBodyAddress;
import wei.yigulu.iec104.nettyconfig.Iec104MasterBuilder;
import wei.yigulu.netty.BaseProtocolBuilder;

import java.util.List;
import java.util.Map;

/**
 * 遥信处理
 *
 * @author 修唯xiuwei
 * @version 3.0
 */
@AsduType(typeId = 1)
public class HandelBoolean extends BooleanType {

	ModusTableService modusTableService = ModusTableService.getInstance();

	/**
	 * 处理短浮点数据
	 *
	 * @param apdu 传入的包文
	 * @return 返回 响应
	 */
	@Override
	public byte[][] handleAndAnswer(Apdu apdu) {
		apdu.getLog().trace("----------处理遥信数据---------");
		BaseProtocolBuilder builder = apdu.getIec104Builder();
		if (builder != null && builder instanceof Iec104MasterBuilder) {
			Map<Integer, ModusTable> dataPoint = (Map<Integer, ModusTable>) builder.getConfigInfoMap().get("ModusTable");
			HandelBoolean handelBoolean = (HandelBoolean) apdu.getAsdu().getDataFrame();
			List<InformationBodyAddress> address = handelBoolean.getAddresses();
			List<IeBoolean> datas = handelBoolean.getDatas();
			int i = 0;
			//存入共享服务端
			ModusTable modusTable;
			if (apdu.getAsdu().getVsq().getSq() == 0) {
				apdu.getLog().trace("------处理遥信单一寻址-----");
				for (IeBoolean e : datas) {
					if (dataPoint.containsKey(address.get(i).getAddress())) {
						modusTable = dataPoint.get(address.get(i).getAddress());
						modusTableService.updateModusValue(modusTable.getIpIdentity(), modusTable.getId(), e.getIecValue() ? "1" : "0", "");
					}
					i++;
				}
			} else if (apdu.getAsdu().getVsq().getSq() == 1) {
				apdu.getLog().trace("------处理遥信连续寻址-----");
				i = address.get(0).getAddress();
				for (IeBoolean e : datas) {
					if (dataPoint.containsKey(i)) {
						modusTable = dataPoint.get(i);
						modusTableService.updateModusValue(modusTable.getIpIdentity(), modusTable.getId(), e.getIecValue() ? "1" : "0", "");
					}
					i++;
				}
			}
		}
		return null;
	}

}
